﻿using System;
using System.Globalization;
using System.Threading.Tasks;
using Casamiel.API.Application;
using Casamiel.API.Application.Services;
using Casamiel.API.Infrastructure;
using Casamiel.API.Infrastructure.Filters;
using Casamiel.Common.Extensions;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Casamiel.API.Controllers.V2
{
    /// <summary>
    /// 购物车
    /// </summary>
    [Produces("application/json")]
    [ApiVersion("2.0")]
    [Route("api/v{api-version:apiVersion}/ShoppingCart")]
    [TypeFilterAttribute(typeof(CheckTokenAttribute))]
    [Authorize]
    [ApiController]
    public class ShoppingCartController : Controller
    {

        private readonly IIcApiService _icApiService;
        private readonly IStoreApiService _storeApiService;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="iicApiService">Iic API service.</param>
        /// <param name="storeApiService">Store API service.</param>
        public ShoppingCartController(IIcApiService iicApiService, IStoreApiService storeApiService)
        {
            _icApiService = iicApiService;
            _storeApiService = storeApiService;
        }
        /// <summary>
        /// 新增更新
        /// </summary>
        /// <param name="data"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        /// <remarks>{"Id":0,"GoodsId":1,"GoodsQuantity":1}</remarks>
        [Route("[Action]")]
        [HttpPost]
        public async Task<IActionResult> InsetOrUpate([FromBody] JObject data, [FromHeader(Name = "u-token")] string token)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }

            var Id = data["Id"].ToInt32(-1);
            var GoodsId = data["GoodsId"].ToInt32(-1);
            var GoodsQuantity = data["GoodsQuantity"].ToInt32(-1);
            var mobile = MemberHelper.GetMobile(token);
            var result = await _storeApiService.ShoppingCartInsetOrUpate(Id, GoodsId, GoodsQuantity, mobile).ConfigureAwait(false);
            var Obj = JsonConvert.DeserializeObject<JObject>(result);
            if (Obj["ResultNo"].ToString() == "00000000") {
                return Ok(new { code = 0, msg = "" });
            } else {
                return Ok(new { code = 999, msg = Obj["ResultRemark"].ToString() });
            }
        }

        /// <summary>
        /// 选中购物车Item
        /// </summary>
        /// <param name="data"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        /// <remarks>Ids，英文，隔开{"Ids":"1,2","isCheck":true}</remarks>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> Checked([FromBody] JObject data, [FromHeader(Name = "u-token")] string token)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }

            string Ids = data["Ids"].ToString();
            bool isCheck = Convert.ToBoolean(data["isCheck"].ToString(), CultureInfo.CurrentCulture);
            var mobile = MemberHelper.GetMobile(token);
            var result = await _storeApiService.ShoppingCartItemsChecked(Ids, isCheck, mobile).ConfigureAwait(false);
            var Obj = JsonConvert.DeserializeObject<JObject>(result);
            if (Obj["ResultNo"].ToString() == "00000000") {
                return Ok(new { code = 0, msg = "" });
            } else {
                return Ok(new { code = 999, msg = Obj["ResultRemark"].ToString() });
            }
        }

        /// <summary>
        /// 删除购物车项
        /// </summary>
        /// <param name="data"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        /// <remarks>Ids，英文，隔开{"Ids":"1,2"}</remarks>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> Delete([FromBody] JObject data, [FromHeader(Name = "u-token")] string token)
        {
            if (data == null) {
                throw new ArgumentNullException(nameof(data));
            }

            string Ids = data["Ids"].ToString();
            bool isCheck = Convert.ToBoolean(data["isCheck"].ToString(), CultureInfo.CurrentCulture);
            var mobile = MemberHelper.GetMobile(token);
            var result = await _storeApiService.ShoppingCartItemsDelete(Ids, mobile).ConfigureAwait(false);
            var Obj = JsonConvert.DeserializeObject<JObject>(result);
            if (Obj["ResultNo"].ToString() == "00000000") {
                return Ok(new { code = 0, msg = "" });
            } else {
                return Ok(new { code = 999, msg = Obj["ResultRemark"].ToString() });
            }
        }

        /// <summary>
        /// 我的购物车
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("[action]")]
        public async Task<IActionResult> GetList([FromHeader(Name = "u-token")] string token)
        {
            var mobile = MemberHelper.GetMobile(token);
            var list = await _storeApiService.GetMyCartList(mobile).ConfigureAwait(false);
            return Ok(new { code = 0, content = list });
        }
    }
}
